package cn.huanghuai.reggie.service.impl;

import cn.huanghuai.reggie.common.BaseContext;
import cn.huanghuai.reggie.common.CustomException;
import cn.huanghuai.reggie.entity.*;
import cn.huanghuai.reggie.mapper.OrdersMapper;
import cn.huanghuai.reggie.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 因为操作了很多次数据库，所以要加入事务控制
     * @param orders
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        Long currentId = BaseContext.getCurrentId();
        Long addressBookId = orders.getAddressBookId();

        //补齐orders中的基础信息
            //user相关信息
        User user = userService.getById(currentId);
        BeanUtils.copyProperties(user, orders, "id");
        orders.setUserName(user.getName());
            //地址相关信息
        AddressBook addressBook = addressBookService.getById(addressBookId);
            //判断地址信息是否异常
        if (addressBook == null){
            throw new CustomException("地址信息有误，不能下单");
        }
        BeanUtils.copyProperties(addressBook, orders, "id");
        orders.setAddress(addressBook.getDetail());
            //生成并设置订单号
        long orderId = IdWorker.getId();
        orders.setNumber(String.valueOf(orderId));
            //购物车菜品相关信息
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lambdaQueryWrapper);
            //判断是否为空下单，如果是空下单则抛出异常
        if (shoppingCartList == null){
            throw new CustomException("购物车为空，不能下单");
        }
            //计算并设置总金额
        AtomicInteger amount = new AtomicInteger(0);
        for (int i = 0; i < shoppingCartList.size(); i++) {
            ShoppingCart shoppingCart = shoppingCartList.get(i);
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
        }
        orders.setAmount(new BigDecimal(amount.get()));
            //设置下单时间,支付时间，订单状态
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);

        //向订单表插入一条数据
        this.save(orders);

        //向订单明细表插入多条菜品信息
            //查询并补全菜品信息
        for (int i = 0; i < shoppingCartList.size(); i ++){
            OrderDetail orderDetail = new OrderDetail();
            ShoppingCart shoppingCart = shoppingCartList.get(i);

            //复制基本信息，除id外
            BeanUtils.copyProperties(shoppingCart, orderDetail,"id");
            //添加订单id
            orderDetail.setOrderId(orders.getId());
            //插入数据到订单明细表
            orderDetailService.save(orderDetail);
        }

        //清空购物车信息
            //添加条件过滤器
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            //添加过滤条件
        lambdaQueryWrapper1.eq(ShoppingCart::getUserId, currentId);
            //执行删除
        shoppingCartService.remove(lambdaQueryWrapper1);
    }
}
